#include <stdio.h>
#include <stdlib.h>
#include <iostream>

#include "../include/RenderWindow.h"

using namespace std;

RenderWindow::RenderWindow(
	int width,
	int height,
	const char * windowTitle,
	int openglProfile,
	int majorVersion,
	int minorVersion,
	bool fullScreen,
	bool currentContext
	)
{
	glfwSetErrorCallback(error_callback);
	if (!glfwInit())
		exit(EXIT_FAILURE);
	if (majorVersion > 0 && minorVersion > 0)
	{
		glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, majorVersion);
		glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, minorVersion);
	}
	
	glfwWindowHint(GLFW_OPENGL_PROFILE, openglProfile);
	
	//TODO specify monitor
	m_window = glfwCreateWindow(width, height, windowTitle, 
		fullScreen ? glfwGetPrimaryMonitor() : NULL, NULL);

	if (!m_window)
	{
		glfwTerminate();
		exit(EXIT_FAILURE);
	}
	if(currentContext)
	{
		glfwMakeContextCurrent(m_window);
	}
	glfwSetKeyCallback(m_window, key_callback);

	int major = glfwGetWindowAttrib(m_window, GLFW_CONTEXT_VERSION_MAJOR);
	int minor = glfwGetWindowAttrib(m_window, GLFW_CONTEXT_VERSION_MINOR);
	cout <<"OpenGL version: " << major <<"." << minor << endl;
}

RenderWindow::~RenderWindow()
{
	glfwDestroyWindow(m_window);
	glfwTerminate();
}


bool RenderWindow::windowShouldClose()
{
	return glfwWindowShouldClose(m_window);
}

void RenderWindow::swapBuffers()
{
	glfwSwapBuffers(m_window);
}

void RenderWindow::getFrameBufferSize(int & width, int & height)
{
	glfwGetFramebufferSize(m_window,&width,&height);
}

void RenderWindow::error_callback(int error, const char* description)
{
	fputs(description, stderr);
}

void RenderWindow::key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
	if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
		glfwSetWindowShouldClose(window, GL_TRUE);
}
